﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CarbonExchange.Bll;

namespace CarbonExchange.Tests
{
    [TestClass]
    public class FootprintSavingTest : BaseTest
    {
        [TestMethod]
        public void GetTopTest()
        {
            FootprintSavingFactory factory = new FootprintSavingFactory();
            var tmp = factory.Get(null, _TestSite.Id, 0, 2);
            
            Assert.IsNotNull(tmp);
            Assert.AreEqual(2, tmp.Count);

            foreach(var item in tmp)
            {
                var audits = _TestAudits.Where(x => x.Completed && x.AcmsUser.Id == item.UserId).OrderByDescending(x => x.EndDate).ToList();
                Assert.AreEqual(3, audits.Count());

                var latestAudit = audits.First();
                var secondAudit= audits.Skip(1).FirstOrDefault();
                var biggestAudit = audits.OrderByDescending(x => x.Answers.Sum(y => y.AnswerItems.Where(z => z.Footprint.HasValue).Sum(z => z.Footprint.Value))).First();
                
                Assert.IsTrue(GetAuditFootprint(biggestAudit) >= GetAuditFootprint(latestAudit));
                Assert.IsNotNull(latestAudit);
                Assert.IsNotNull(secondAudit);
                Assert.IsNotNull(biggestAudit);

                var latestFootprint = GetAuditFootprint(latestAudit);
                var lastFootprint = GetAuditFootprint(secondAudit);
                var biggestFootprint = GetAuditFootprint(biggestAudit);

                Assert.IsTrue(latestFootprint > 0);
                Assert.IsTrue(lastFootprint > 0);
                Assert.IsTrue(biggestFootprint > 0);

                Assert.AreEqual(latestFootprint, item.LatestFootprint);
                Assert.AreEqual(lastFootprint, item.PreviousFootprint);
                Assert.AreEqual(biggestFootprint, item.MaxFootprint);
            }
        }

        private decimal GetAuditFootprint(CarbonExchange.Dal.Audit audit)
        {
            return audit.Answers.Sum(x => x.AnswerItems.Sum(y => y.Footprint ?? 0m));
        }
    }
}
